var prefix = "/order/refund";
$(function () {
    layui.use('laydate', function(){
        var laydate = layui.laydate;
        laydate.render({
            elem: '#start'
            ,type: 'datetime'
        });

        laydate.render({
            elem: '#end'
            ,type: 'datetime'
        });
    });

    load();
});
$('#orderTable').on('load-success.bs.table', function (e, data) {
    if (data.total && !data.rows.length) {
        $('#orderTable').bootstrapTable('selectPage').bootstrapTable('refresh');
    }
});

function load() {
    $('#orderTable').bootstrapTable(
        {
            method: 'get', // 服务器数据的请求方式 get or post
            url: prefix + "/list", // 服务器数据的加载地址
            showRefresh: true,
            // showToggle : true,
            iconSize: 'outline',
            // toolbar: '#exampleToolbar',
            striped: true, // 设置为true会有隔行变色效果
            dataType: "json", // 服务器返回的数据类型
            pagination: true, // 设置为true会在底部显示分页条
            pageList: [10, 20, 50],
            // queryParamsType : "limit",
            // //设置为limit则会发送符合RESTFull格式的参数
            singleSelect: false, // 设置为true将禁止多选
            // contentType : "application/x-www-form-urlencoded",
            // //发送到服务器的数据编码类型
            pageSize: 10, // 如果设置了分页，每页数据条数
            pageNumber: 1, // 如果设置了分布，首页页码
            // search : true, // 是否显示搜索框
            showColumns: false, // 是否显示内容下拉框（选择显示的列）
            sidePagination: "server", // 设置在哪里进行分页，可选值为"client" 或者
            queryParams: function (params) {
                return {
                    limit: params.limit,
                    offset: params.offset,
                    order: 'desc',
                    queryItem: $.trim($("#queryItem").val()),
                    centreId: $("*[name='centreId']").val(),
                    start: $('#start').val(),
                    end: $('#end').val()
                };
            },
            columns: [
                {checkbox: true},
                {
                    field: 'id',
                    title: '订单ID'
                },
                {
                    field: 'goodstotal',
                    title: '商品信息',
                    formatter: function (value, row, index) {
                        return formatProductInfo(row.orderProducts, row.order.ordersn, row.refundsn);
                    }
                },
                {
                    field: 'mid',
                    title: '买家信息',
                    formatter: function (value, row, index) {
                        var order = row.order;
                        var dispatchtype = '门店家自提';
                        if (order.dispatchtype != 0) {
                            dispatchtype = '直邮';
                        }
                        var m = '<p>'+ "所属门店:"+ order.tNickname+ '<span class="label label-primary">'+dispatchtype+'</span></p>';
                        var d = '<p>' + "自提地址:" + order.address + '</p>';
                        var s = '<p>' + "下单人:" + order.nickname + '</p>';
                        var r = '<p>' + "收货人:" + order.sname + '</p>';
                        var p = '<p>' + "手机号:" + order.mobile + '</p>';
                        return m + d + s + r + p;
                    }
                },
                {
                    field: 'goodsprice',
                    title: '费用',
                    formatter: function (value, row, index) {
                        var order = row.order;

                        var no_info = '<p>支付单号:'+ order.payno+'</p>' + '<p>商户单号:'+ order.payMerchantNo+'</p>';
                        var payType = order.paytype;
                        var py = '';
                        if (payType === 1) {
                            py = '<label class="label label-danger">余额支付</label>';
                        }else if (payType === 2) {
                            py = '<label class="label label-success">微信支付</label>';
                        }else {
                            py = '<label class="label label-info">微信+余额</label>';
                        }

                        var p = '<p style="margin-top: 20px">' + "商品小计:" + order.goodsprice + '</p>';
                        var d = '<p>' + "运费:" + order.dispatchprice + '</p>';
                        var pp = '<p style="color: green">' + "应付:" + order.payprice + '</p>';
                        return no_info + py + p + d + pp;
                    }
                },
                {
                    field: 'createTime',
                    title: '时间',
                    formatter: function (value, row, index) {
                        var order = row.order;
                        var c = '<p>下单时间:' + order.createTime + '</p>';
                        var p = '<p>支付时间:' + order.payTime + '</p>';
                        var a = '<p>申请时间:' + value + '</p>';
                        return a + c + p;
                    }
                },
                {
                    field: 'status',
                    title: '状态',
                    formatter: function (value, row, index) {
                        if (value == -1) {
                            return '<label class="label label-default">已拒绝</label>'
                        } else if (value == 0) {
                            return '<label class="label label-danger">待审核</label>'
                        } else if (value == 1) {
                            return '<label class="label label-info">已审核</label>'
                        } else if (value == 2) {
                            return '<label class="label label-warning">已退款</label>'
                        }
                    }
                },
                {
                    title: '操作',
                    field: 'id',
                    align: 'center',
                    formatter: function (value, row, index) {
                        var detail = '<a class="btn btn-success btn-xs ' + s_detail_h + '" href="#" mce_href="#" title="详情" onclick="detail(\''
                            + row.oid + '\')">' + '<i class="fa fa-eye"></i>查看详细</a>';


                        var refund_check = '<a class="btn btn-danger btn-xs ' + s_refund_check_h + '" href="#" mce_href="#" title="审核" onclick="refundCheck(\''
                            + value + '\')">' + '<i class="fa fa-recycle"></i>申请审核</a>';

                        var close = '<a class="btn btn-default btn-xs ' + s_close_h + '" href="#" mce_href="#" title="失效" onclick="refundClose(\''
                            + value + '\')">' + '<i class="fa fa-remove"></i>退款失效</a>';

                        return detail + '<br>'+ refund_check + '<br>' + close;
                    }
                }]
        });
}
function reLoad() {
    $('#orderTable').bootstrapTable('refresh');
}

/**
 * 格式化商品列信息
 * @param orderProducts 订单商品列表
 * @param orderSn 订单编号
 */
function formatProductInfo(orderProducts, orderSn, refundsn) {
    var info = "<span class='label label-light'>订单编号:" + orderSn + "</span>" +'<br>' + "<span class='label label-light'>退款单号:" + refundsn + "</span>" +'<br>';
    if (orderProducts && orderProducts.length >0) {
        for (var i=0; i<orderProducts.length; i++) {
            var item = orderProducts[i];
            info = info
                +'<table class="table">'
                +'<tbody>'
                +'<tr>'
                +'<td style="width: 50px"><img src='+ item.thumb+' style="width:50px;height:50px"></td>'
                +'<td style="border: 0px">'+ item.productName+ '<br>'
                +'</td>'
                +'<td style="text-align:right;border: 0px">' +
                '         '+'原价:'+item.productprice +'<br>'
                +'应付:'+item.marketprice +'<br>'
                +'数量:'+item.total +'<br>'
                + '</td>'
                + '</tr>'
                + '</tbody>'
                +'</table>'
        }
    }
    return info;
}

/**
 * 订单详情页面
 * @param orderId
 */
function detail(orderId) {
    layer.open({
        id: 'order_detail',
        type: 2,
        title: '订单详情',
        maxmin: true,
        shadeClose: false,
        area: ['60%', '80%'],
        content: "/order/manage" + '/detail/' + orderId // iframe的url
    });
}


/**
 * 退款审核
 * @param refundId
 */
function refundCheck(refundId) {
    layer.confirm('确定提交给财务打款吗？', {
        btn: ['确定', '取消']
    }, function () {
        $.ajax({
            url: prefix + "/refundCheck",
            type: "POST",
            data: {
                'refundId': refundId
            },
            beforeSend: function (request) {
                index = layer.load();
            },
            success: function (r) {
                if (r.code == 0) {
                    layer.close(index);
                    layer.msg(r.msg);
                    reLoad();
                } else {
                    layer.msg(r.msg);
                }
            }
        });
    })
}
/**
 * 失效退款
 * @param refundId
 */
function refundClose(refundId) {
    layer.confirm('确认退款订单失效？', {
        btn: ['确定', '取消']
    }, function () {
        $.ajax({
            url: prefix + "/refundClose",
            type: "POST",
            data: {
                'refundId': refundId
            },
            beforeSend: function (request) {
                index = layer.load();
            },
            success: function (r) {
                if (r.code == 0) {
                    layer.close(index);
                    layer.msg(r.msg);
                    reLoad();
                } else {
                    layer.msg(r.msg);
                }
            }
        });
    })
}

function batchCheck() {
    var rows = $('#orderTable').bootstrapTable('getSelections'); // 返回所有选择的行，当没有选择的记录时，返回一个空数组
    if (rows.length === 0) {
        layer.msg("请选择要审核的数据");
        return;
    }
    layer.confirm("确认要审核选中的'" + rows.length + "'条数据吗?", {
        btn: ['确定', '取消']
        // 按钮
    }, function () {
        var ids = [];
        // 遍历所有选择的行数据，取每条数据对应的ID
        $.each(rows, function (i, row) {
            ids[i] = row['id'];
        });
        $.ajax({
            type: 'POST',
            data: {
                "ids": ids
            },
            url: prefix + '/batchCheck',
            success: function (r) {
                if (r.code === 0) {
                    layer.msg(r.msg);
                    reLoad();
                } else {
                    layer.msg(r.msg);
                }
            }
        });
    }, function () {
    });
}